﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;

namespace SlickGridNet.Serialization
{
	public abstract class SlickSuffixBaseConverter: JsonConverter
	{
		protected abstract string Suffix { get; }
		public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
		{
			// Try to get explicit name of IExplicitObject
			var explicitObject = value as IExplicitObject;
			if (explicitObject == null)
				throw new ArgumentException("ExplicitObjectConverter can convert value only of IExplicitObject type.");
			var explicitName = explicitObject.ExplicitName;

			// If explicit name not defined get it from type's FullName
			if (explicitName == null)
			{
				string fullName = value.GetType().FullName;
				if (fullName.EndsWith(Suffix) && fullName.Length != Suffix.Length)
					fullName = fullName.Substring(0, fullName.Length - Suffix.Length);
				explicitName = fullName;
			}
			writer.WriteRawValue(explicitName);
		}
	}
}
